package com.imooc.bilibili.support;

import com.imooc.bilibili.exception.ConditionException;
import com.imooc.bilibili.util.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户相关支持
 *
 * @author gcq
 * @Create 2022-05-23
 */
@Component
public class UserSupport {

    /**
     * 获取请求头中的token信息，拿到userId
     *
     * @return userId
     */
    public Long getCurrentUserId() {
        // 获取请求上下文内容
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if(request == null) {
            throw new ConditionException("非法用户");
        }
        String token = request.getHeader("token"); // 从请求头中获取到token
        Long userId = TokenUtil.verifyToken(token); // 获取当前请求token
        if(userId < 0) {
            throw new ConditionException("非法用户");
        }
        return userId;
    }

}